package com.beemans.corekit.ui.activity;

import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

import com.beemans.corekit.integration.toolkit.ActivityUtils;

public class PermissionActivity extends BaseActivity<ViewBinding> {
    public static final String PARAMS_PERMISSION = "PARAMS_PERMISSION";

    @Nullable
    private String[] permissions = null;
    @Nullable
    private static Runnable permissionCallback = null;

    @Nullable
    @Override
    protected ViewBinding getViewBinding() {
        return null;
    }

    @Override
    public void initData(@Nullable Bundle extras) {
        if (extras != null) {
            permissions = extras.getStringArray(PARAMS_PERMISSION);
        }
    }

    @Override
    protected void initViews() {
    }

    @Override
    protected void initEvents() {
        if (permissions == null || permissions.length == 0) {
            ActivityUtils.finishActivity(this, false);

            if (permissionCallback != null) {
                permissionCallback.run();
            }

            return;
        }

        final ActivityResultLauncher<String[]> launcher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                result -> {
                    ActivityUtils.finishActivity(this, false);

                    if (permissionCallback != null) {
                        permissionCallback.run();
                    }
                }
        );

        launcher.launch(permissions);
    }

    public static void start(@NonNull String[] permissions, @NonNull Runnable callback) {
        permissionCallback = callback;

        final Bundle bundle = new Bundle();
        bundle.putStringArray(PARAMS_PERMISSION, permissions);
        ActivityUtils.startActivity(PermissionActivity.class, bundle);
    }
}